package com.az.miaoauth.listener;

import com.az.emailcommon.util.EmailSender;
import com.az.miaoapi.dto.MUserDto;
import com.az.miaoapi.exception.BaseException;
import com.az.miaoauth.domain.po.TheUser;
import com.az.miaoauth.mapper.TheUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@RequiredArgsConstructor
public class MUpdateListener {

    private final EmailSender emailSender;
    private final TheUserMapper theUserMapper;
    private final PasswordEncoder passwordEncoder;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "mupdate_queue", durable = "true"),
            exchange = @Exchange(value = "muser.direct"),
            key = {"mupdate_key"}))
    @Retryable(noRetryFor = BaseException.class)
    public void mupdate(MUserDto mUserDto) {
        TheUser theUser = Optional
                .ofNullable(theUserMapper.selectById(mUserDto.getUserId()))
                .orElseThrow(() -> new MessageConversionException("用户不存在"));
        theUser.setUsername(mUserDto.getUsername());
        theUser.setPassword(passwordEncoder.encode(mUserDto.getPassword()));
        theUserMapper.updateById(theUser);
        emailSender.sendSimpleEmail(
                theUser.getEmail(),
                "账户信息修改成功",
                "您的账户信息已被修改，如非本人操作，请及时联系客服");
        System.out.println("我听到了！！！");
    }
}
